#include "sharedmemory.h"

Boolean CreateSharedConstantString(String Name, String Value, Handle &hFileMappingObject)
{
	Boolean Result;
	PSharedMemoryHeader pHeader = NULL;

	Result = FALSE;
	hFileMappingObject = 0;
	__try
	{
		hFileMappingObject = CreateFileMappingA(
			INVALID_HANDLE_VALUE,
			NULL,
			PAGE_READWRITE,
			0,
			sizeof(TSharedMemoryHeader) + strlen(Value),
			Name
		);
		if (hFileMappingObject == 0) return FALSE;

		pHeader = (PSharedMemoryHeader)MapViewOfFile(
			hFileMappingObject,
			FILE_MAP_WRITE,
			0,
			0,
			0
		);
		if (pHeader == NULL) return FALSE;

		(*pHeader).Size = strlen(Value);

		if (strlen(Value) > 0)
		{
			sprintf(PChar(pHeader + sizeof(TSharedMemoryHeader)),"%s",Value);
			/*Move(
				Value[1],
				PChar(pHeader + sizeof(TSharedMemoryHeader))^,
				strlen(Value)
			);*/
		};

		//WriteBarrier();

		(*pHeader).Initialized = TRUE;
		Result = TRUE;
	}
	__finally
	{
		if (pHeader != NULL)
		{
			UnmapViewOfFile(pHeader);
		}

		if ((Result == FALSE) && (hFileMappingObject != 0))
		{
			CloseHandle(hFileMappingObject);
		}
	}
	return Result;
};

Boolean GetSharedConstantString(String Name, String Value)
{
	Boolean Result;
	Handle hFileMappingObject = 0;
	PSharedMemoryHeader pHeader = NULL;
	//UnicodeString uName;

	Result = FALSE;
	sprintf(Value,"%s","");

	__try
	{
		hFileMappingObject = OpenFileMappingA(
			FILE_MAP_READ,
			FALSE,
			Name
		);
		if (hFileMappingObject == 0) return FALSE;

		pHeader = (PSharedMemoryHeader)MapViewOfFile(hFileMappingObject, FILE_MAP_READ, 0, 0, 0);
		if (pHeader == NULL) return FALSE;

		if (!(*pHeader).Initialized) return FALSE;

		if ((*pHeader).Size > 0)
		{
			Value = new char[(*pHeader).Size];
			sprintf(Value,"%s",PChar(pHeader + sizeof(TSharedMemoryHeader)));
			/*Move(
				PChar(pHeader + sizeof(TSharedMemoryHeader))^,
				Value[1],
				Length(Value)
			);*/
		};

		Result = TRUE;
	}
	__finally
	{
		if (pHeader != NULL)
		{
			UnmapViewOfFile(pHeader);
		}

		if (hFileMappingObject != 0)
		{
			CloseHandle(hFileMappingObject);
		}
	};
	return Result;
};
